<template>
	<!-- 导航栏 -->
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>内容管理</el-breadcrumb-item>
		<el-breadcrumb-item>文章管理</el-breadcrumb-item>
	</el-breadcrumb>

	<!-- 行内表单 -->
	<el-form :inline="true" :model="queryInfo" class="demo-form-inline" style="padding: 15px 0">
		<el-form-item label="文章名">
			<el-input v-model="queryInfo.articleName" placeholder="请输入文章名" clearable @clear="queryDataList" />
		</el-form-item>

		<el-form-item label="咨询师作者" style="width: 200px">
			<el-select v-model="queryInfo.consultantId" placeholder="请选择咨询师" clearable @clear="queryDataList">
				<el-option v-for="item in consultants" :key="item.value" :label="item.consultantName"
					:value="item.id" />
			</el-select>
		</el-form-item>

		<el-form-item label="选择分类" style="width: 200px">
			<el-select v-model="queryInfo.sort" placeholder="请选择分类" clearable @clear="queryDataList">
				<el-option v-for="item in options" :key="item.value" :label="item.sortName" :value="item.id" />
			</el-select>
		</el-form-item>

		<el-form-item>
			<el-button type="primary" @click="queryDataList">搜索</el-button>
			<el-button type="success" @click="add">新增文章</el-button>
			<el-button type="danger" @click="removeBatch">批量删除</el-button>
		</el-form-item>
	</el-form>

	<!-- 数据表格 -->
	<!-- data:绑定的数据；row-key:以后的每一行的主键；style:样式宽度  -->
	<el-table :data="dataList" border row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
		<el-table-column fixed="left" type="selection" width="55" />
		<el-table-column fixed="left" property="id" label="ID" width="60" />
		<el-table-column property="articleName" label="文章名" />
		<el-table-column property="articleDes" label="文章简介" />
		<el-table-column property="consultant.consultantName" label="咨询师名" />
		<el-table-column property="articlePic" label="缩略图">
			<template #default="scope">
				<el-avatar shape="square" size="large"
					:src="'http://localhost:8080' + scope.row.articlePic"></el-avatar>
			</template>
		</el-table-column>
		<el-table-column property="articleReadCount" label="阅读量" />
		<el-table-column property="articleSort.sortName" label="所属分类" />
		<el-table-column property="articleTime" label="创建时间" />
		<el-table-column property="articleStatus" label="审核状态">
			<template #default="scope">
				<el-tag type="primary" v-if="scope.row.articleStatus == 0">审核中</el-tag>
				<el-tag type="success" v-else-if="scope.row.articleStatus == 1">审核通过</el-tag>
				<el-tag type="danger" v-else>审核未通过</el-tag>
			</template>
		</el-table-column>
		<el-table-column property="del" label="状态">
			<template #default="scope">
				<el-tag type="success" v-if="scope.row.del == 0">正常</el-tag>
				<el-tag type="danger" v-else>已删除</el-tag>
			</template>
		</el-table-column>
		<el-table-column fixed="right" label="操作" min-width="120">
			<template #default="scope">
				<el-button type="success" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<!-- 分页区域 -->
	<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
		:page-sizes="[5, 10, 15, 20]" size="default" default-page-size="5"
		layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
		@current-change="handleCurrentChange" />

	<!-- Dialog对话框 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="950" @close="cancle">
		<el-form :model="articleDate" label-width="100">
			<el-form-item label="文章标题">
				<el-input v-model="articleDate.articleName" autocomplete="off" placeholder="请输入文章标题"></el-input>
			</el-form-item>
			<el-form-item label="文章简介">
				<el-input v-model="articleDate.articleDes" placeholder="请输入文章简介"></el-input>
			</el-form-item>

			<el-form-item label="咨询师作者">
				<el-select v-model="articleDate.consultantId" placeholder="请选择咨询师作者" style="height: 40px">
					<el-option v-for="item in consultants" :key="item.value" :label="item.consultantName"
						:value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="缩略图">
				<!-- 上传组件
						action:必选参数，上传的地址
						list-type:文件列表的类型
						on-success:文件上传成功时的回调函数
						limit:最大允许上传个数
						on-preview:点击文件列表中已上传的文件时的钩子
						file-list:上传的文件列表
						on-mremove:文件列表移除文件时的钩子
				 -->
				<el-upload action="http://localhost:8080/upload" list-type="picture-card" :on-success="handleSuccess"
					:limit="1" :on-preview="handlePictureCardPreview" :file-list="fileList" :on-remove="handleRemove">
					<el-icon style="
              width: 128px;
              height: 128px;
              border: 1px dashed #dcdfe6;
              border-radius: 5px;
              font-size: 20px;
            ">
						<Plus />
					</el-icon>
				</el-upload>
				<!-- 放大预览组件: 和官网一致 -->
				<el-dialog v-model="dialogVisible">
					<img w-full :src="dialogImageUrl" alt="Preview Image" />
				</el-dialog>
			</el-form-item>

			<el-form-item label="文章内容详情">
				<div class="editor-wrapper">
					<QuillEditor v-model:content="articleDate.articleDetails" contentType="html"
						:options="editorOptions" />
				</div>
			</el-form-item>

			<el-form-item label="所属分类">
				<el-select v-model="articleDate.sort" placeholder="请选择分类">
					<el-option v-for="item in options" :key="item.value" :label="item.sortName" :value="item.id" />
				</el-select>
			</el-form-item>

			<el-form-item label="文章状态">
				<el-select v-model="articleDate.articleStatus" placeholder="请更改文章状态">
					<el-option label="审核中" value="0" />
					<el-option label="审核通过" value="1" />
					<el-option label="审核未通过" value="2" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { ElMessage, ElMessageBox } from 'element-plus'
	import { Plus } from '@element-plus/icons-vue'
	import { getCurrentInstance, onMounted, reactive, ref, nextTick } from 'vue'
	import type { FormInstance, UploadProps } from 'element-plus'
	import { QuillEditor } from '@vueup/vue-quill'
	import '@vueup/vue-quill/dist/vue-quill.snow.css'
	import { cloneDeep } from 'lodash-es'

	// 查询对象信息
	const queryInfo = reactive({
		id: '',
		articleName: '',
		consultantId: '',
		sort: '',
		del: 0,
		pageNum: 1,
		pageSize: 5,
	})

	// 总数据量
	const total = ref()

	const dataList = ref([])

	const options = ref([])

	const consultants = ref([])

	const axios = getCurrentInstance().appContext.config.globalProperties.axios

	const queryConsultantList = () => {
		axios.get('consultant/all').then((resp) => {
			console.log()
			if (resp.code == 200) {
				consultants.value = resp.data
			} else {
				ElMessage.error(resp.message)
			}
		})
	}

	const querySortList = () => {
		axios.get('articleSort').then((resp) => {
			console.log()
			if (resp.code == 200) {
				options.value = resp.data
			} else {
				ElMessage.error(resp.message)
			}
		})
	}

	// 定义查询数据的函数
	const queryDataList = () => {
		axios
			.get('article/page', {
				params: queryInfo,
			})
			.then((resp) => {
				console.log(resp.data.list)
				if (resp.code == 200) {
					dataList.value = resp.data.list
					total.value = resp.data.total
				} else {
					ElMessage.error(resp.message)
				}
			})
	}

	// 组件加载完毕，加载数据
	onMounted(() => {
		queryDataList()

		querySortList()
		queryConsultantList()
	})

	// 存储复选的数据
	const multipleSelection = ref([])

	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map((item) => {
			return item.id
		})
		console.log(multipleSelection.value)
	}

	/* 每页显示条目数改变 */
	const handleSizeChange = (val : number) => {
		queryInfo.pageNum = 1
		queryInfo.pageSize = val
		queryDataList()
	}
	/* 页码改变 */
	const handleCurrentChange = (val : number) => {
		queryInfo.pageNum = val
		queryDataList()
	}

	const title = ref('新增文章')

	const dialogFormVisible = ref(false)

	const articleDate = ref({
		id: '',
		articleName: '',
		articleDes: '',
		consultantId: '',
		articlePic: '',
		articleDetails: '',
		articleReadCount: '',
		sort: '',
		articleTime: '',
		articleStatus: '0',
		del: 0,
		consultant: {
			id: '',
			consultantName: '',
		},
		articleSort: {
			id: '',
			sortName: '',
			del: 0,
		},
	})

	const cancle = () => {
		console.log('你点击了取消按钮')
		articleDate.value = {
			id: '',
			articleName: '',
			articleDes: '',
			consultantId: '',
			articlePic: '',
			articleDetails: '<p></p>',
			articleReadCount: '',
			sort: '',
			articleTime: '', // 这里建议为 '' 或 0
			articleStatus: '0', // 这里建议为 '0'，但如果类型为 number 则为 0
			del: 0,
			consultant: {
				id: '',
				consultantName: '',
			},
			articleSort: {
				id: '',
				sortName: '',
				del: 0,
			},
		}
		// 保证articleDetails为字符串
		articleDate.value.articleDetails = articleDate.value.articleDetails || ''
		dialogFormVisible.value = false
		fileList.value = []
	}
	const confirm = () => {
		if (articleDate.value.id) {
			axios.put('article/edit', articleDate.value).then((resp) => {
				if (resp.code == 200) {
					ElMessage.success(resp.message)
				} else {
					ElMessage.error(resp.message)
				}
				queryDataList()
				dialogFormVisible.value = false
			})
		} else {
			console.log('你点击了确定按钮')
			axios.post('/article/add', articleDate.value).then((resp) => {
				if (resp.code == 200) {
					ElMessage.success(resp.message)
				} else {
					ElMessage.error(resp.message)
				}
				queryDataList()
				dialogFormVisible.value = false
			})
		}
	}

	const add = () => {
		title.value = '新增文章'
		dialogFormVisible.value = true
		nextTick(() => {
			window.dispatchEvent(new Event('resize'))
		})
	}

	const edit = (row) => {
		title.value = '编辑文章'
		dialogFormVisible.value = true

		row.articleStatus = row.articleStatus + ''
		articleDate.value = cloneDeep(row)
		articleDate.value.sort = row.articleSort?.id || ''
		fileList.value = []
		var listView = articleDate.value.articlePic
		if (listView) {
			fileList.value.push({
				name: listView.substr(listView.lastIndexOf('/') + 1),
				url: 'http://localhost:8080' + listView,
			})
		}
	}
	// 图片上传
	const dialogImageUrl = ref('') // 图片预览框的地址
	const dialogVisible = ref(false) // 控制图片预览框是否显示
	const fileList = ref([])

	// 上传成功的回调，res服务器响应的数据
	const handleSuccess = (resp, file) => {
		articleDate.value.articlePic = resp.data
		fileList.value = [
			{
				name: file.name,
				url: 'http://localhost:8080' + resp.data,
			},
		]
	}
	// 图片删除处理
	const handleRemove = () => {
		articleDate.value.articlePic = ''
		fileList.value = []
	}
	// 图片预览处理
	const handlePictureCardPreview = (file) => {
		dialogImageUrl.value = file.url
		dialogVisible.value = true
	}

	const remove = (id) => {
		ElMessageBox.confirm('此操作将永久删除文件，是否继续?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
			center: true,
		})
			.then(() => {
				axios.delete(`article/${id}`).then((resp) => {
					if (resp.code == 200) {
						ElMessage.success(resp.message)
					} else {
						ElMessage.error(resp.message)
					}
					queryDataList()
				})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}

	const removeBatch = () => {
		ElMessageBox.confirm('此操作将永久删除文件，是否继续?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
			center: true,
		})
			.then(() => {
				axios.delete(`article?ids=${multipleSelection.value.join(',')}`).then((resp) => {
					if (resp.code == 200) {
						ElMessage.success(resp.message)
					} else {
						ElMessage.error(resp.message)
					}
					queryDataList()
				})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}

	/* 富文本编辑器 */
	const content = ref('')
	const show = () => {
		console.log(content.value)
	}
	const editorOptions = reactive({
		theme: 'snow', // 使用 snow 主题
		modules: {
			toolbar: [
				['bold', 'italic', 'underline', 'strike'], // 加粗、斜体、下划线、删除线
				['blockquote', 'code-block'], //引用，代码块
				[{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
				[{ list: 'ordered' }, { list: 'bullet' }], // 有序列表、无序列表
				[{ indent: '-1' }, { indent: '+1' }], // 缩进
				[{ size: ['small', false, 'large', 'huge'] }], // 字体大小
				[{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
				[{ font: [] }], //字体
				[{ align: [] }], //对齐方式
				['link', 'image'], // 链接、图片
			],
		},
	})
</script>

<style>
	.el-breadcrumb {
		/* 下划线 */
		border-bottom: 1px solid #eeeeee;
		padding-bottom: 15px;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	.el-pagination {
		margin-top: 15px;
	}

	.editor-container {
		padding: 20px;
		background: #fff;
		border-radius: 4px;
	}

	:deep(.ql-container) {
		min-height: 350px;
		width: 100%;
	}

	/* 修正上传组件样式 */
	:deep(.el-upload--picture-card) {
		width: 128px;
		height: 128px;
		line-height: 128px;
	}

	/* 图片预览样式 */
	:deep(.el-upload-list--picture-card .el-upload-list__item) {
		width: 128px;
		height: 128px;
	}

	:deep(.ql-container) {
		min-height: 420px;
		max-height: 700px;
		width: 100%;
		border-radius: 6px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
		background: #fff;
	}

	.el-form-item .ql-container {
		margin-bottom: 12px;
	}

	:deep(.ql-toolbar) {
		background: #f8f8f8;
		border-radius: 6px 6px 0 0;
	}

	:deep(.ql-container) {
		border-radius: 0 0 6px 6px;
	}

	:deep(.ql-container) {
		min-height: 350px;
		max-height: 600px;
		overflow-y: auto;
	}

	.editor-wrapper {
		width: 100%;
		min-height: 120px;
		/* 没内容时的固定高度 */
		border: 2px solid #eeeeee;
		/* 黑色边框 */
		border-radius: 6px;
		box-sizing: border-box;
		padding: 0;
		margin-bottom: 16px;
		background: #fff;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
	}

	:deep(.ql-container) {
		min-height: 120px;
		/* 没内容时的固定高度 */
		max-height: 600px;
		/* 内容多时最大高度 */
		width: 100%;
		border-radius: 0 0 6px 6px;
		background: #fff;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
		overflow-y: auto;
		/* 超出最大高度时滚动 */
		transition: min-height 0.2s;
	}
</style>